package com.vpx.server.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vpx.server.bean.entity.*;
import com.vpx.server.bean.enums.UserDataRangeEnum;
import com.vpx.server.bean.info.base.UserInfo;
import com.vpx.server.bean.info.system.SysUserInfo;
import com.vpx.server.bean.info.system.UserRoleInfo;
import com.vpx.server.bean.order.base.BaseDeleteOrder;
import com.vpx.server.bean.order.base.BaseIdOrder;
import com.vpx.server.bean.order.system.*;
import com.vpx.server.bean.result.system.SysUserPageResult;
import com.vpx.server.bean.result.system.SysUserResult;
import com.vpx.server.bean.result.system.SysUserRoleResult;
import com.vpx.server.framework.aop.ServiceHandler;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.exception.BizException;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.framework.utils.PasswordUtil;
import com.vpx.server.mapper.system.*;
import com.vpx.server.service.system.SysUidService;
import com.vpx.server.service.system.SysUserService;
import com.vpx.server.utils.UserLoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuks
 * @title: vpx
 * @module: 用户管理
 * @description: 用户管理服务
 * @date 2021/09/11 13:35
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;



    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUidService sysUidService;

    @Override
    @ServiceHandler(memo = "新增用户", isTransaction = true)
    public ResultMsg insert(SysUserOrder order) {
        if (checkUserLoginAccountExist(null, order.getLoginAccount())) {
            throw new BizException("登录账号已存在");
        }
        SysUser user = new SysUser();
        user.from(order);
//        user.setUserCode(String.valueOf(sysUidService.getNextNum(SysUidService.TYPE_1001)));
        user.setLoginPwd(PasswordUtil.getDefaultPassword());
        user.setCreateUserId(UserLoginUtils.getCurrentUser().getId());
        user.setUpdateUserId(UserLoginUtils.getCurrentUser().getId());
        user.setCreateTime(DateUtils.now());
        user.setUpdateTime(DateUtils.now());
        sysUserMapper.insert(user);

        return new ResultMsg();
    }

    @Override
    @ServiceHandler(memo = "修改用户", isTransaction = true)
    public ResultMsg updateById(SysUserOrder order) {
        SysUser user = sysUserMapper.selectById(order.getId());
        if (user == null) {
            throw new BizException("未查询到用户信息");
        }
        if (checkUserLoginAccountExist(order.getId(), order.getLoginAccount())) {
            throw new BizException("登录账号已存在");
        }
        user.from(order);
        user.setUpdateUserId(UserLoginUtils.getCurrentUser().getId());
        user.setUpdateTime(DateUtils.now());
        sysUserMapper.updateById(user);
        return new ResultMsg();
    }

    @Override
    @ServiceHandler(memo = "删除用户", isTransaction = true)
    public ResultMsg deleteById(BaseDeleteOrder order) {
        sysUserMapper.deleteById(order.getId());
        sysUserRoleMapper.deleteSysUserRoleByUserId(order.getId());
        return new ResultMsg();
    }

    @Override
    @ServiceHandler(memo = "查询用户")
    public ResultMsg<SysUserResult> findById(BaseIdOrder order) {
        SysUser user = sysUserMapper.selectById(order.getId());
        if (user == null) {
            throw new BizException("未查询到用户信息");
        }
        SysUserInfo userInfo = sysUserMapper.selectUserById(order.getId());
        SysUserResult userResult = new SysUserResult();
        userResult.setUserInfo(userInfo);
        return ResultMsg.success(userResult);
    }

    @Override
    @ServiceHandler(memo = "分页查询用户")
    public ResultMsg<SysUserPageResult> pageQuery(SysUserPageOrder order) {
        if (order.getPageNum() != null && order.getPageSize() != null) {
            PageHelper.startPage(order.getPageNum(), order.getPageSize());
        }
        List<SysUserInfo> sysUserInfos = sysUserMapper.pageQuery(order);
        PageInfo<SysUserInfo> pageInfo = new PageInfo<SysUserInfo>(sysUserInfos);
        SysUserPageResult userPageResult = new SysUserPageResult();
        userPageResult.setPageInfo(pageInfo);
        return ResultMsg.success(userPageResult);
    }

    @Override
    @ServiceHandler(memo = "查询用户角色")
    public ResultMsg<SysUserRoleResult> findUserRoleById(BaseIdOrder order) {
        List<SysRole> roleList = sysRoleMapper.queryAllSysRole();
        List<SysUserRole> userRoleList = sysUserRoleMapper.querySysUserRoleByUserId(order.getId());
        List<UserRoleInfo> userRoleInfos = new ArrayList<UserRoleInfo>();
        UserRoleInfo userRoleInfo = null;
        for (SysRole role : roleList) {
            userRoleInfo = new UserRoleInfo();
            userRoleInfo.setRoleId(role.getId());
            userRoleInfo.setRoleName(role.getRoleName());
            for (SysUserRole userRole : userRoleList) {
                if (role.getId().longValue() == userRole.getRoleId().longValue()) {
                    userRoleInfo.setHasRoleAuth(true);
                }
            }
            userRoleInfos.add(userRoleInfo);
        }
        SysUserRoleResult result = new SysUserRoleResult();
        result.setUserRoleInfos(userRoleInfos);
        return ResultMsg.success(result);
    }

    @Override
    @ServiceHandler(memo = "保存用户角色", isTransaction = true)
    public ResultMsg saveUserRoleList(UserRoleListOrder order) {
        sysUserRoleMapper.deleteSysUserRoleByUserId(order.getUserRoleList().get(0).getUserId());
        List<UserRoleOrder> userRoleListOrder = order.getUserRoleList();
        List<SysUserRole> sysUserRoles = new ArrayList<SysUserRole>();
        SysUserRole sysUserRole = null;
        for (UserRoleOrder userRoleOrder : userRoleListOrder) {
            sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userRoleOrder.getUserId());
            sysUserRole.setRoleId(userRoleOrder.getRoleId());
            sysUserRole.setCreateUserId(UserLoginUtils.getCurrentUser().getId());
            sysUserRole.setUpdateUserId(UserLoginUtils.getCurrentUser().getId());
            sysUserRole.setCreateTime(DateUtils.now());
            sysUserRole.setUpdateTime(DateUtils.now());
            sysUserRoles.add(sysUserRole);
        }
        sysUserRoleMapper.insertBatch(sysUserRoles);
        return new ResultMsg();
    }

    @Override
    @ServiceHandler(memo = "重置用户密码", isTransaction = true)
    public ResultMsg resetUserPassword(BaseIdOrder order) {
        SysUser user = sysUserMapper.selectById(order.getId());
        if (user == null) {
            throw new BizException("未查询到用户信息");
        }
        user.setLoginPwd(PasswordUtil.getDefaultPassword());
        sysUserMapper.updateById(user);
        return new ResultMsg();
    }

    @Override
    @ServiceHandler(memo = "修改用户密码", isTransaction = true)
    public ResultMsg updateUserPassword(UserPasswordOrder order) {
        UserInfo userInfo = UserLoginUtils.getCurrentUser();
        SysUser user = sysUserMapper.selectById(userInfo.getId());
        if (!PasswordUtil.getPassword(order.getOldPassword()).equals(user.getLoginPwd())) {
            throw new BizException("原始密码不正确");
        }
        user.setLoginPwd(PasswordUtil.getPassword(order.getNewPassword()));
        sysUserMapper.updateById(user);
        return new ResultMsg();
    }



    @ServiceHandler(memo = "检查用户登录账户是否存在")
    private boolean checkUserLoginAccountExist(Long id, String loginAccount) {
        if (id == null) {
            int count = sysUserMapper.querySysUserCountByLoginAccount(loginAccount);
            return count > 0 ? true : false;
        }
        int countOne = sysUserMapper.querySysUserCountByIdAndLoginAccount(id, loginAccount);
        if (countOne == 1) {
            return false;
        }
        int countTwo = sysUserMapper.querySysUserCountByLoginAccount(loginAccount);
        return countTwo > 0 ? true : false;
    }


}
